import 'package:flutter/material.dart';

import '../config/app_colors.dart';



class LoadingUtil {
  static bool _isShowing = false;
  static BuildContext? _context;
  static OverlayEntry? _overlayEntry;

  static void show(BuildContext context) {
    if (!_isShowing && context.mounted) {
      _context = context;
      _isShowing = true;
      
      try {
      _overlayEntry = OverlayEntry(
        builder: (context) {
          return Container(
            color: Colors.black.withOpacity(0.3),
            child: Center(
              child: Container(
                width: 100,
                height: 100,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children:[
                    CircularProgressIndicator(
                      color: AppColors.primary,
                    ),
                    const SizedBox(height: 16),
                    Text(
                      'Loading...',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey[700],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      );

        if (_context != null && _context!.mounted) {
          Overlay.of(_context!).insert(_overlayEntry!);
        }
      } catch (e) {
        debugPrint('LoadingUtil show error: $e');
        _isShowing = false;
        _context = null;
        _overlayEntry = null;
      }
    }
  }

  static void close() {
    if (_isShowing && _overlayEntry != null) {
      try {
        _overlayEntry?.remove();
      } catch (e) {
        debugPrint('LoadingUtil close error: $e');
      } finally {
        _overlayEntry = null;
      _isShowing = false;
        _context = null;
      }
    }
  }
  
  static bool get isShowing => _isShowing;
  
  static void forceClose() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _isShowing = false;
    _context = null;
  }
}
